import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/bottom_sheet.dart';
import 'package:hj_crm/utils/form_photo.dart';
import 'package:hj_crm/utils/form_utils.dart';
import 'package:hj_crm/utils/image_utils.dart';
import 'package:hj_crm/utils/toast_utils.dart';

/// 用户表单
class DistributorFormWidget extends StatefulWidget {
  final String? uId;

  const DistributorFormWidget({super.key, this.uId});

  @override
  State<DistributorFormWidget> createState() => _DistributorFormState();
}

class _DistributorFormState extends State<DistributorFormWidget> {
  RequestRepository repository = Get.find<RequestRepository>();
  final _formKey = GlobalKey<FormBuilderState>();

  String? avatarPath = '';

  bool isCooperation = false; // 是否合作
  bool samplesFlag = false; // 是否邮寄样品

  String _registeredMount = ''; // 注册资金

  late TextEditingController _nameController;
  late TextEditingController _legalController;
  late TextEditingController _addressController;

  late TextEditingController _registeredCapitalController; // 注册资金
  late TextEditingController _employeeNumberController; // 在职人数
  late TextEditingController _annualSalesController; // 年销售额
  late TextEditingController _operatingLifeController; // 经营年限

  late TextEditingController _mainProductsController; // 主营产品
  late TextEditingController _businessModeController; // 经营方式
  late TextEditingController _contactInfoController; // 联系方式
  late TextEditingController _wechatIdController; // 微信号
  late TextEditingController _dealerSourceController; // 客户来源
  late TextEditingController _postProductController; // 邮寄样品
  late TextEditingController _serviceUserController; // 服务专员

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _legalController = TextEditingController();
    _addressController = TextEditingController();

    _registeredCapitalController = TextEditingController(); // 注册资金
    _employeeNumberController = TextEditingController(); // 在职人数
    _annualSalesController = TextEditingController(); // 年销售额
    _operatingLifeController = TextEditingController(); // 经营年限

    _mainProductsController = TextEditingController(); // 主营产品
    _businessModeController = TextEditingController(); // 经营方式
    _contactInfoController = TextEditingController(); // 联系方式
    _wechatIdController = TextEditingController(); // 微信号
    _dealerSourceController = TextEditingController(); // 客户来源
    _postProductController = TextEditingController(); // 邮寄样品
    _serviceUserController = TextEditingController(); // 服务专员

    if (widget.uId != null) {
      repository.findDistributorInfo(
          id: widget.uId!,
          success: (data) {
            avatarPath = data.businessLicense;
            _nameController.text = data.customerName ?? '';
            _legalController.text = data.legal ?? '';
            _registeredCapitalController.text =
                data.registeredCapital != null ? '${data.registeredCapital!.toInt()}万' : '';
            _employeeNumberController.text =
                data.employeeNumber != null ? employeeNumbersData[data.employeeNumber!] : '';
            _annualSalesController.text =
                data.annualSales != null ? annualSalesData[data.annualSales!.toInt()] : '';
            _operatingLifeController.text = data.operatingLife ?? '';
            _mainProductsController.text = data.mainProducts ?? '';
            _businessModeController.text = data.businessMode ?? '';
            _contactInfoController.text = data.contactInfo ?? '';
            _wechatIdController.text = data.wechatId ?? '';
            _dealerSourceController.text = data.dealerSource ?? '';
            _postProductController.text = data.postProduct ?? '';
            _serviceUserController.text = data.serviceUser ?? '';
            _addressController.text = data.companyAddress ?? '';

            _formKey.currentState?.patchValue({
              'isCooperation': data.isCooperation,
              'samplesFlag': data.isSendSample,
            });
          });
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _addressController.dispose();
    _legalController.dispose();

    _registeredCapitalController.dispose(); // 注册资金
    _employeeNumberController.dispose(); // 在职人数
    _annualSalesController.dispose(); // 年销售额
    _operatingLifeController.dispose(); // 经营年限
    _mainProductsController.dispose(); // 主营产品
    _businessModeController.dispose(); // 经营方式
    _contactInfoController.dispose(); // 联系方式
    _wechatIdController.dispose(); // 微信号
    _dealerSourceController.dispose(); // 客户来源
    _postProductController.dispose(); //
    _serviceUserController.dispose(); // 服务专员
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('新增客户'),
        ),
        body: SingleChildScrollView(
          child: FormBuilder(
            key: _formKey,
            autovalidateMode: AutovalidateMode.disabled,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: const Text('经销商基本信息',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                  ),
                  FormPhotoWidget(
                    path: avatarPath,
                    tips: '点击上传营业执照',
                    onTap: () {
                      openImageBottomSheet((index) {
                        ImageUtils.selectImage(
                          kind: index == 0 ? ImageSourceKind.image : ImageSourceKind.camera,
                          result: (bytesData) {
                            repository.imageUpload(
                              bytesData: bytesData,
                              fileName: '${DateTime.now().millisecondsSinceEpoch}.jpg',
                              success: (data) {
                                setState(() {
                                  avatarPath = data.first as String?;
                                });
                              },
                              fail: (code, msg) {
                                ToastUtils.show(msg);
                              },
                            );
                          },
                        );
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'name',
                    decoration: const InputDecoration(labelText: '企业名称'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '企业名称不能为空'),
                    ]),
                    keyboardType: TextInputType.text,
                    controller: _nameController,
                    textInputAction: TextInputAction.next,
                  ),
                  FormBuilderTextField(
                    name: 'legal',
                    decoration: const InputDecoration(labelText: '法人'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '法人名字不能为空'),
                    ]),
                    keyboardType: TextInputType.text,
                    controller: _legalController,
                    textInputAction: TextInputAction.next,
                  ),
                  FormBuilderTextField(
                    name: 'address',
                    decoration: const InputDecoration(labelText: '企业地址'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '企业地址不能为空'),
                    ]),
                    keyboardType: TextInputType.text,
                    controller: _addressController,
                    textInputAction: TextInputAction.done,
                    onEditingComplete: () {
                      if (GetPlatform.isAndroid) {
                        FocusScope.of(context).unfocus();
                        return;
                      }
                      FocusScope.of(context).nextFocus();
                    },
                  ),
                  SizedBox(height: 20),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: const Text('规模',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                  ),
                  FormBuilderTextField(
                    name: 'registeredCapital',
                    decoration: InputDecoration(labelText: '注册资金', hintText: '100万'),
                    keyboardType: rcMask.textInputType,
                    inputFormatters: [rcMask.formatter],
                    controller: _registeredCapitalController,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      //
                      if (_registeredMount.isNotEmpty &&
                          !_registeredCapitalController.text.contains('万')) {
                        _registeredCapitalController.text = '${_registeredCapitalController.text}万';
                      }
                    },
                    onTapOutside: (event) {
                      if (_registeredMount.isNotEmpty &&
                          !_registeredCapitalController.text.contains('万')) {
                        _registeredCapitalController.text = '${_registeredCapitalController.text}万';
                      }
                    },
                    onChanged: (value) => _registeredMount = value ?? '',
                    onSubmitted: (value) => FocusScope.of(context).unfocus(),
                  ),
                  FormBuilderTextField(
                    name: 'employeeNumber',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '在职人数'),
                    controller: _employeeNumberController,
                    onTap: () {
                      openEmployeeNumberPicker(context, (value) {
                        _employeeNumberController.text = value;
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'annualSales',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '年销售额'),
                    controller: _annualSalesController,
                    onTap: () {
                      openAnnualSalesPicker(context, (value) {
                        _annualSalesController.text = value;
                      });
                    },
                  ),
                  FormBuilderTextField(
                    name: 'operatingLife',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '经营年限'),
                    controller: _operatingLifeController,
                    onTap: () {
                      openOperatingLifePicker(context, (value) {
                        _operatingLifeController.text = value;
                      });
                    },
                    onSubmitted: (value) => FocusScope.of(context).nextFocus(),
                  ),
                  SizedBox(height: 20),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: const Text('其他信息',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                  ),
                  FormBuilderTextField(
                    name: 'mainProducts',
                    decoration: const InputDecoration(labelText: '主营产品'),
                    controller: _mainProductsController,
                    textInputAction: TextInputAction.next,
                    keyboardType: TextInputType.text,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  FormBuilderTextField(
                    name: 'businessMode',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '经营方式'),
                    controller: _businessModeController,
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '经营方式不能为空'),
                    ]),
                    onTap: () {
                      openBusinessModePicker(context, (value) {
                        _businessModeController.text = value;
                      });
                    },
                    onSubmitted: (value) => FocusScope.of(context).nextFocus(),
                  ),
                  FormBuilderTextField(
                    name: 'contactInfo',
                    decoration: const InputDecoration(labelText: '联系方式'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '联系方式不能为空'),
                      FormBuilderValidators.numeric(errorText: '手机号码格式不正确'),
                      FormBuilderValidators.minLength(11, errorText: '手机号码格式不正确'),
                      FormBuilderValidators.maxLength(11, errorText: '手机号码格式不正确'),
                    ]),
                    controller: _contactInfoController,
                    textInputAction: TextInputAction.next,
                    keyboardType: TextInputType.phone,
                    onEditingComplete: () {
                      if (GetPlatform.isAndroid) {
                        FocusScope.of(context).unfocus();
                        return;
                      }
                      FocusScope.of(context).nextFocus();
                    },
                  ),
                  FormBuilderTextField(
                    name: 'wechatId',
                    decoration: const InputDecoration(labelText: '微信号'),
                    controller: _wechatIdController,
                    keyboardType: TextInputType.name,
                    textInputAction: TextInputAction.next,
                    onSubmitted: (value) => FocusScope.of(context).unfocus(),
                  ),
                  FormBuilderTextField(
                    name: 'dealerSource',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '客户来源'),
                    controller: _dealerSourceController,
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '客户来源不能为空'),
                    ]),
                    onTap: () {
                      openDealerSourcePicker(context, (value) {
                        _dealerSourceController.text = value;
                      });
                    },
                  ),
                  FormBuilderSwitch(
                    name: 'isCooperation',
                    initialValue: isCooperation,
                    selected: isCooperation,
                    title: Text('是否合作'),
                    onChanged: (value) {
                      isCooperation = value ?? false;
                    },
                  ),
                  FormBuilderSwitch(
                    name: 'samplesFlag',
                    initialValue: samplesFlag,
                    selected: samplesFlag,
                    title: Text('是否邮递样品'),
                    onChanged: (value) {
                      setState(() {
                        samplesFlag = value ?? false;
                      });
                    },
                  ),

                  /// 邮寄样品
                  if (samplesFlag)
                    FormBuilderTextField(
                      name: 'postProduct',
                      decoration: const InputDecoration(labelText: '邮寄样品'),
                      controller: _postProductController,
                      textInputAction: TextInputAction.next,
                      keyboardType: TextInputType.text,
                    ),
                  FormBuilderTextField(
                    name: 'serviceUser',
                    decoration: const InputDecoration(labelText: '服务专员'),
                    controller: _serviceUserController,
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.done,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      /// 验证表单
                      if (!_formKey.currentState!.saveAndValidate()) {
                        return;
                      }

                      if (_registeredCapitalController.text.contains('万')) {
                        _registeredCapitalController.text = _registeredCapitalController.text
                            .substring(0, _registeredCapitalController.text.length - 1);
                      }

                      /// 提交数据
                      Map<String, dynamic> map = {
                        'id': widget.uId ?? '',
                        'customerName': _nameController.text,
                        'legal': _legalController.text,
                        'businessLicense': avatarPath,
                        'companyAddress': _addressController.text,
                        'registeredCapital': _registeredCapitalController.text,
                        'employeeNumber':
                            employeeNumbersData.indexOf(_employeeNumberController.text),
                        'annualSales': annualSalesData.indexOf(_annualSalesController.text),
                        'operatingLife': _operatingLifeController.text,
                        'mainProducts': _mainProductsController.text,
                        'businessMode': _businessModeController.text,
                        'contactInfo': _contactInfoController.text,
                        'wechatId': _wechatIdController.text,
                        'dealerSource': _dealerSourceController.text,
                        'isCooperation': isCooperation,
                        'isSendSample': samplesFlag,
                        'serviceUser': _serviceUserController.text,
                        'postProduct': _postProductController.text,
                      };

                      if (widget.uId == null || widget.uId == '') {
                        repository.addDistributor(
                            params: map,
                            success: (data) {
                              Navigator.pop(context, true);
                            },
                            fail: (code, msg) {});
                      } else {
                        repository.updateDistributor(
                            params: map,
                            success: (data) {
                              Navigator.pop(context, true);
                            },
                            fail: (code, msg) {});
                      }
                    },
                    child: const Text('保存'),
                  ),
                  SizedBox(height: 20),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
